package com.hbm.usercenter.base;

import android.text.TextUtils;

import com.hbm.usercenter.conf.Constants;
import com.hbm.usercenter.fragment.LoginFragment;
import com.hbm.usercenter.fragment.PhLoginFragment;
import com.hbm.usercenter.http.NetClient;
import com.hbm.usercenter.utils.FileUtils;
import com.hbm.usercenter.utils.IOUtils;
import com.hbm.usercenter.utils.LogUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import static com.hbm.usercenter.conf.Constants.URLS.BASEURL;

public abstract class BaseProtocol<T> {

    public T loadData(int index) throws Exception {
        /*--------------- 首先从本地加载数据 ---------------*/
        T t = getDataFromLocal(index);
        if (t != null && Constants.isCache) {
            LogUtils.s("###从本地加载数据-->" + getCacheFile(index).getAbsolutePath());
            return t;
        }

		/*--------------- 得到jsonString的过程 ---------------*/
        T result = getDataFromNet(index);
        return result;
    }

    /**
     * 从网络加载数据
     */
    private String mResult;

    private T getDataFromNet(int index) throws IOException {
        LogUtils.s("###请求网络数据-->");
        String url = BASEURL + getInterfaceKey();
        Map<String, String> extraParams = getExtraParams();
        if (extraParams != null) {
            mResult = NetClient.getNetClient().callNetSync(url, extraParams);
        } else {
            mResult = NetClient.getNetClient().callNetSync(url);
        }



		/*--------------- 保存对应的jsonString ---------------*/

        File cacheFile = getCacheFile(index);
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(cacheFile));
            writer.write(System.currentTimeMillis() + "");
            writer.write("\r\n");
            writer.write(mResult);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(writer);
        }
        LogUtils.s("######mResult-->" + mResult);
        T parseJson = parseJson(mResult);
        return parseJson;
    }


    /**
     * 从本地加载数据
     *
     * @param index
     * @return
     */
    private T getDataFromLocal(int index) {

        try {
            File cacheFile = getCacheFile(index);
            if (cacheFile.exists()) {
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(cacheFile));
                    // 读取插入时间
                    String timeStr = reader.readLine();
                    long time = Long.parseLong(timeStr);
                    // 判断是否过期
                    if (System.currentTimeMillis() - time < Constants.PROTOCOLTIMEOUT) {
                        String cacheJsonString = reader.readLine();
                        return parseJson(cacheJsonString);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.close(reader);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;

    }

    private File getCacheFile(int index) {
        String dir = FileUtils.getDir("json");
        Map<String, String> extraParams = getExtraParams();
        String name = "";
        if (extraParams != null) {
            String s = transfromDir(getInterfaceKey());
            name = s + "." + index;
        } else {
            String s = transfromDir(getInterfaceKey());
            name = s + "." + index;
        }
        File cacheFile = new File(dir, name);
        LogUtils.s("路径为------：" + cacheFile.getAbsolutePath());
        return cacheFile;
    }

    private String transfromDir(String dir) {
        String filename = null;
        String name1 = LoginFragment.getName();
        String name2 = PhLoginFragment.getName();

//        int i = dir.indexOf("?");
        int i = dir.lastIndexOf("/");
        String substring = dir.substring(0, i);
        String replace = substring.replace("/", "");
        if (!TextUtils.isEmpty(name1)) {
            filename = replace + name1;
        } else {
            filename = replace + name2;
        }
        LogUtils.s("filename-----"+filename);
        return filename;
    }

    /**
     * @return
     * @des 传递额外的参数, 默认情况是null
     * @call 子类可以覆写该方法, 传递具体额外的参数
     */
    protected Map<String, String> getExtraParams() {
        return null;
    }

    protected abstract T parseJson(String result);

    protected abstract String getInterfaceKey();
}
